﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using TfsCommitMonitor.Properties;
using TfsCommitMonitor.Tfs;

namespace TfsCommitMonitor
{
	internal class TfsChangesetListView : TfsListView
    {
        private ColumnHeader _changesetColumn;
		private ColumnHeader _dateColumn;
		private ColumnHeader _committorColumn;
		private ColumnHeader _commentColumn;

		internal TfsChangesetListView()
		{
            InitializeComponents();
			MultiSelect = true;			
		}

        private void InitializeComponents()
        {
            _changesetColumn = new ColumnHeader();
            _changesetColumn.Text = Resources.TfsListView_TfsChangesetListView_Header_Changeset;
            _changesetColumn.Width = 70;

			_dateColumn = new ColumnHeader();
			_dateColumn.Text = Resources.TfsListView_TfsChangesetListView_Header_Date;
            _dateColumn.Width = 120;

			_committorColumn = new ColumnHeader();
			_committorColumn.Text = Resources.TfsListView_TfsChangesetListView_Header_Committor;
			_committorColumn.Width = 150;

			_commentColumn = new ColumnHeader();
			_commentColumn.Text = Resources.TfsListView_TfsChangesetListView_Header_Comment;
			_commentColumn.Width = 300;

            Columns.AddRange(
                new[]
                {
                    _changesetColumn,
                    _dateColumn,
					_committorColumn,
					_commentColumn,
                });
        }

		internal void DisplayChangsets(IEnumerable<Changeset> changesets)
		{
			BeginUpdate();
			SuspendLayout();
			try
			{
				Items.AddRange(
					changesets.Select(CreateListViewItem)
					.ToArray());
			}
			finally
			{
				ResumeLayout();
				EndUpdate();
			}
		}

		private ListViewItem CreateListViewItem(Changeset changeset)
		{
			var listViewItem = new ListViewItem(changeset.ChangesetId.ToString())
			{
				Tag = changeset,
			};

			if (!changeset.Read)
				listViewItem.Font = new Font(Font, FontStyle.Bold);

			listViewItem.SubItems.AddRange(
				GetListViewSubItemText(changeset).ToArray());

			return listViewItem;
		}

		private static IEnumerable<String> GetListViewSubItemText(Changeset changeset)
		{
			yield return
				String.Format("{0} {1}", changeset.CreationDate.ToShortDateString(), changeset.CreationDate.ToShortTimeString());
			yield return 
				changeset.Committor;
			yield return 
				changeset.Comment;
		}
	}
}
